package com.ruoyi.gateway.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.gateway.domain.DeviceMap;
import com.ruoyi.gateway.domain.dto.TopicTransformResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.gateway.mapper.TopicMapMapper;
import com.ruoyi.gateway.domain.TopicMap;
import com.ruoyi.gateway.service.ITopicMapService;

/**
 * 主题映射Service业务层处理
 *
 * @author 白向阳
 * @date 2025-09-28
 */
@Service
public class TopicMapServiceImpl implements ITopicMapService
{
    @Autowired
    private TopicMapMapper topicMapMapper;

    // 缓存主题映射
    private final Map<String, TopicMap> topicCache = new HashMap<>();

    /**
     * 查询主题映射
     *
     * @param id 主题映射主键
     * @return 主题映射
     */
    @Override
    public TopicMap selectTopicMapById(Long id)
    {
        return topicMapMapper.selectTopicMapById(id);
    }

    /**
     * 查询主题映射列表
     *
     * @param topicMap 主题映射
     * @return 主题映射
     */
    @Override
    public List<TopicMap> selectTopicMapList(TopicMap topicMap)
    {
        return topicMapMapper.selectTopicMapList(topicMap);
    }

    /**
     * 新增主题映射
     *
     * @param topicMap 主题映射
     * @return 结果
     */
    @Override
    public int insertTopicMap(TopicMap topicMap)
    {
        topicMap.setCreateTime(DateUtils.getNowDate());
        return topicMapMapper.insertTopicMap(topicMap);
    }

    /**
     * 修改主题映射
     *
     * @param topicMap 主题映射
     * @return 结果
     */
    @Override
    public int updateTopicMap(TopicMap topicMap)
    {
        topicMap.setUpdateTime(DateUtils.getNowDate());
        return topicMapMapper.updateTopicMap(topicMap);
    }

    /**
     * 批量删除主题映射
     *
     * @param ids 需要删除的主题映射主键
     * @return 结果
     */
    @Override
    public int deleteTopicMapByIds(Long[] ids)
    {
        return topicMapMapper.deleteTopicMapByIds(ids);
    }

    /**
     * 删除主题映射信息
     *
     * @param id 主题映射主键
     * @return 结果
     */
    @Override
    public int deleteTopicMapById(Long id)
    {
        return topicMapMapper.deleteTopicMapById(id);
    }


    /**
     * 设备主题转换为平台主题
     */
    @Override
    public TopicTransformResult transformDeviceToPlatform(String deviceTopic, DeviceMap deviceMapping) {
        loadTopicCacheIfNeeded();

        // 查找匹配的主题映射
        for (TopicMap topicMap : topicCache.values()) {
            if ("up".equals(topicMap.getDirection()) &&
                    matchTopicPattern(deviceTopic, topicMap.getDeviceTopicPattern())) {

                String platformTopic = buildPlatformTopic(topicMap.getPlatformTopicPattern(), deviceMapping);
                return new TopicTransformResult(platformTopic, deviceTopic);
            }
        }

        // 默认转换规则
        return defaultDeviceToPlatformTransform(deviceTopic, deviceMapping);
    }

    /**
     * 平台主题转换为设备主题
     */
    @Override
    public TopicTransformResult transformPlatformToDevice(String platformTopic, DeviceMap deviceMapping) {
        loadTopicCacheIfNeeded();

        // 查找匹配的主题映射
        for (TopicMap topicMap : topicCache.values()) {
            if ("down".equals(topicMap.getDirection()) &&
                    matchTopicPattern(platformTopic, topicMap.getPlatformTopicPattern())) {

                String deviceTopic = buildDeviceTopic(topicMap.getDeviceTopicPattern(), deviceMapping);
                return new TopicTransformResult(platformTopic, deviceTopic);
            }
        }

        // 默认转换规则
        return defaultPlatformToDeviceTransform(platformTopic, deviceMapping);
    }

    /**
     * 默认的设备到平台主题转换
     */
    private TopicTransformResult defaultDeviceToPlatformTransform(String deviceTopic, DeviceMap deviceMapping) {
        // 根据设备主题类型进行转换
        if (deviceTopic.contains("/device/state")) {
            // 设备状态上报 -> 平台属性上报
            String platformTopic = String.format("/%s/%s/property/post",
                    deviceMapping.getPlatformProductId(),
                    deviceMapping.getPlatformDeviceSerialNumber());
            return new TopicTransformResult(platformTopic, deviceTopic);
        }

        // 其他默认转换规则...
        return new TopicTransformResult(deviceTopic, deviceTopic); // 默认不转换
    }

    /**
     * 默认的平台到设备主题转换
     */
    private TopicTransformResult defaultPlatformToDeviceTransform(String platformTopic, DeviceMap deviceMapping) {
        // 根据平台主题类型进行转换
        if (platformTopic.contains("/function/get")) {
            // 功能获取 -> 设备控制
            String deviceTopic = String.format("/jiasion/device/control/%s",
                    deviceMapping.getClientClientId());
            return new TopicTransformResult(platformTopic, deviceTopic);
        } else if (platformTopic.contains("/device/update")) {
            // 设备升级 -> 固件升级
            String deviceTopic = String.format("/jiasion/srv/swupdate/%s",
                    deviceMapping.getClientClientId());
            return new TopicTransformResult(platformTopic, deviceTopic);
        }

        // 其他默认转换规则...
        return new TopicTransformResult(platformTopic, platformTopic); // 默认不转换
    }

    /**
     * 构建平台主题
     */
    private String buildPlatformTopic(String platformPattern, DeviceMap deviceMapping) {
        return platformPattern
                .replace("{product_id}", deviceMapping.getPlatformProductId())
                .replace("{device_serial_number}", deviceMapping.getPlatformDeviceSerialNumber());
    }

    /**
     * 构建设备主题
     */
    private String buildDeviceTopic(String devicePattern, DeviceMap deviceMapping) {
        return devicePattern
                .replace("{device_id}", deviceMapping.getClientClientId());
    }

    /**
     * 匹配主题模式
     */
    private boolean matchTopicPattern(String topic, String pattern) {
        // 将模式转换为正则表达式
        String regex = pattern
                .replace("{product_id}", "[^/]+")
                .replace("{device_serial_number}", "[^/]+")
                .replace("{device_id}", "[^/]+")
                .replace("/", "\\/");

        return Pattern.matches(regex, topic);
    }

    /**
     * 加载主题映射缓存
     */
    private synchronized void loadTopicCacheIfNeeded() {
        if (topicCache.isEmpty()) {
            List<TopicMap> allTopics = topicMapMapper.selectAll();
            for (TopicMap topic : allTopics) {
                String cacheKey = topic.getDirection() + ":" + topic.getDeviceTopicPattern();
                topicCache.put(cacheKey, topic);
            }
        }
    }

    /**
     * 刷新主题映射缓存
     */
    @Override
    public void refreshTopicCache() {
        topicCache.clear();
        loadTopicCacheIfNeeded();
    }
}
